package com.tanhua.server.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.AppraisalMapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Appraisal;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.TestSoulApi;
import com.tanhua.dubbo.server.pojo.Identification;
import com.tanhua.dubbo.server.pojo.Option;
import com.tanhua.dubbo.server.pojo.Question;
import com.tanhua.dubbo.server.pojo.TestSoulQuestionnaire;
import com.tanhua.dubbo.server.vo.Answer;
import com.tanhua.dubbo.server.vo.Dimension;
import com.tanhua.dubbo.server.vo.DimensionType;
import com.tanhua.dubbo.server.vo.Similar;
import com.tanhua.server.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TestSoulService {

    @Reference(version = "1.0.0")
    private TestSoulApi testSoulApi;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AppraisalMapper appraisalMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String TANHUA_TEST_SOUL_PREFIX = "TEST_SOUL_PREFIX_";

    private String getTanhuaTestSoulPrefix(Long userId) {
        return TANHUA_TEST_SOUL_PREFIX + userId;
    }


    /**
     * 业务层:实现功能:测灵魂问卷列表
     *
     * @return
     */
    public ArrayList<TestSoulQuestionnaireVo> getTestSoulList() {
        ArrayList<TestSoulQuestionnaireVo> list = new ArrayList<>();
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        try {

            //1.获取系统推荐的灵魂问卷列表
            List<TestSoulQuestionnaire> testSoulQuestionnaires = testSoulApi.getTestSoulQuestionnaires(userId);

            //2.封装灵魂问卷列表信息
            for (TestSoulQuestionnaire testSoulQuestionnaire : testSoulQuestionnaires) {
                TestSoulQuestionnaireVo testSoulQuestionnaireVo = new TestSoulQuestionnaireVo();
                BeanUtils.copyProperties(testSoulQuestionnaire, testSoulQuestionnaireVo, "id");
                testSoulQuestionnaireVo.setId(testSoulQuestionnaire.getId().toHexString());

                //获取每个问卷中的题目编号id
                List<ObjectId> questionIds = testSoulQuestionnaire.getQuestionIds();

                //获取题目编号对应的题目对象
                List<Question> questions = testSoulApi.getQuestions(questionIds);

                //获取每个题目的选项
                ArrayList<QuestionVo> questionVos = new ArrayList<>();
                for (Question question : questions) {
                    QuestionVo questionVo = new QuestionVo();
                    BeanUtils.copyProperties(question, questionVo, "id");
                    questionVo.setId(question.getId().toHexString());

                    List<Option> options = testSoulApi.getOptions(question.getOptionIds());
                    ArrayList<OptionVo> optionVos = new ArrayList<>();
                    for (Option option : options) {
                        OptionVo optionVo = new OptionVo();
                        BeanUtils.copyProperties(option, optionVo, "id");
                        optionVo.setId(option.getId().toHexString());
                        optionVos.add(optionVo);
                    }
                    questionVo.setOptions(optionVos);
                    questionVos.add(questionVo);
                }
                testSoulQuestionnaireVo.setQuestions(questionVos);

                if (testSoulApi.searchReportId(userId, testSoulQuestionnaire.getId()) != null) {
                    testSoulQuestionnaireVo.setReportId(testSoulApi.searchReportId(userId, testSoulQuestionnaire.getId()));
                }
                //testSoulQuestionnaireVo.setIsLock(1);
                String testSoul = redisTemplate.opsForValue().get(getTanhuaTestSoulPrefix(userId));
                if ("初级".equals(testSoulQuestionnaireVo.getLevel())) {
                    testSoulQuestionnaireVo.setIsLock(0);
                } else {
                    if (StrUtil.isEmpty(testSoul)) {
                        testSoulQuestionnaireVo.setIsLock(1);
                    } else {
                        if (Convert.toInt(redisTemplate.opsForValue().get(getTanhuaTestSoulPrefix(userId))) == 1 && "高级".equals(testSoulQuestionnaireVo.getLevel())) {
                            testSoulQuestionnaireVo.setIsLock(1);
                        } else {
                            testSoulQuestionnaireVo.setIsLock(0);
                        }
                    }
                }
                list.add(testSoulQuestionnaireVo);
            }
        } catch (Exception e) {
            return null;
        }
        return list;
    }

    /**
     * 查看问卷报告
     *
     * @param reportId
     * @return
     */
    public IdentificationVo getIdentificationVo(String reportId) {
        try {
            //获取用户信息
            User user = UserThreadLocal.get();
            Long userId = user.getId();
            //创建返回结果的报告对象
            IdentificationVo identificationVo = new IdentificationVo();
            //通过报告id获取identification对象
            Identification identification = testSoulApi.getIdentification(reportId);
            //封装报告信息
            identificationVo.setConclusion(identification.getConclusion());
            identificationVo.setCover(identification.getCover());
            List<Dimension> dList = new ArrayList<>();
            //封装维度信息
            dList.add(new Dimension(DimensionType.EXTROVERSION.getDesc(), identification.getDimensions().get(0) + "%"));
            dList.add(new Dimension(DimensionType.JUDGE.getDesc(), identification.getDimensions().get(1) + "%"));
            dList.add(new Dimension(DimensionType.ABSTRACT.getDesc(), identification.getDimensions().get(2) + "%"));
            dList.add(new Dimension(DimensionType.REASON.getDesc(), identification.getDimensions().get(3) + "%"));
            identificationVo.setDimensions(dList);


            List<Similar> sList = new ArrayList<>();
            //查找相似的用户，封装用户信息
            for (Long userSimilarId : identification.getSimilarYou()) {
                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id", userSimilarId);
                UserInfo userInfo = this.userInfoMapper.selectOne(wrapper);
                Similar similar = new Similar();
                similar.setAvatar(userInfo.getLogo());
                similar.setId(userInfo.getUserId());
                sList.add(similar);
            }
            identificationVo.setSimilarYou(sList);
            //返回报告信息
            return identificationVo;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 业务层实现功能:测灵魂提交问卷,需要时返回报告id
     *
     * @param answers
     * @return
     */
    public String postTestSoul(Answer[] answers) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        Identification identification = testSoulApi.postTestSoul(answers, userId);
        //获取平均维度值
        List<Integer> dimensions = identification.getDimensions();
        Integer avage = 0;
        for (Integer dimension : dimensions) {
            avage = avage + dimension;
        }
        avage = avage / dimensions.size();
        QueryWrapper<Appraisal> query = new QueryWrapper<>();
        query.eq("level", avage / 8);
        Appraisal appraisal = appraisalMapper.selectOne(query);
        identification.setCover(appraisal.getCover());
        //设置
        identification.setConclusion(appraisal.getConclusion());
        try {
            identification.getSimilarYou();
        } catch (Exception e) {
            identification.setSimilarYou(new ArrayList<>());
        }
        testSoulApi.save(identification);

        //根据问卷编号查询级别
        ObjectId questionnaireId = identification.getQuestionnaireId();
        String level = testSoulApi.getLevel(questionnaireId);
        if (StrUtil.isNotEmpty(level) && StrUtil.equals(level, "初级")) {
            redisTemplate.opsForValue().set(getTanhuaTestSoulPrefix(userId), "1");
        }
        if (StrUtil.isNotEmpty(level) && StrUtil.equals(level, "中级")) {
            redisTemplate.opsForValue().set(getTanhuaTestSoulPrefix(userId), "2");
        }
        //返回报告编号
        return identification.getId().toHexString();
    }


}
